package com.bentley.kotlindemo.websocket

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okio.ByteString
import java.util.concurrent.TimeUnit

/**
 *
 *
 * @author lee
 * @since 2021/04/07 10:57
 */
class WsSocketManagerkt private constructor() {
    companion object {
        val instance by lazy {
            WsSocketManagerkt()
        }
    }

    init {
        initSocket()
    }

    var mWbSocketUrl: String? = null
    var mClient: OkHttpClient? = null
    var mWebSocket: WebSocket? = null

    fun initSocket() {
        mWbSocketUrl = "ws://jimu.test/websocket";
        mClient = OkHttpClient().newBuilder().pingInterval(10, TimeUnit.SECONDS).build()
        val request = Request.Builder().url(mWbSocketUrl).build()
        mWebSocket = mClient?.newWebSocket(request, WsListenerkt())
    }

    fun send(msg: String) {
        mWebSocket?.send(msg)
    }

    fun send(msg: ByteString) {
        mWebSocket?.send(msg)
    }

    fun disconnect(code: Int, reason: String) {
        mWebSocket?.close(code, reason)
    }
}